from fastapi import APIRouter, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse
from openai import OpenAI
import base64
import re

router = APIRouter(tags=["图像处理"])

# DashScope API 配置
client = OpenAI(
    api_key='sk-972207085f3b472b99f78b06a98ef7dd',  # 替换为你的 DashScope API 密钥
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

# 允许的文件类型
ALLOWED_FILE_TYPES = ["image/jpeg", "image/png"]

def encode_image_to_base64(image_data):
    """将图片转换为 Base64 编码"""
    return base64.b64encode(image_data).decode("utf-8")

def text_to_json(text):
    """将文本数据转换为 JSON 格式"""
    # 使用正则表达式提取信息
    food_name_match = re.search(r"食物名称：([\u4e00-\u9fa5a-zA-Z]+)", text)
    weight_match = re.search(r"重量：([\u4e00-\u9fa5a-zA-Z0-9]+)", text)
    calories_match = re.search(r"热量：([\u4e00-\u9fa5a-zA-Z0-9]+)", text)

    # 提取结果
    food_name = food_name_match.group(1) if food_name_match else "未知食物"
    weight = weight_match.group(1) if weight_match else "未知重量"
    calories = calories_match.group(1) if calories_match else "未知热量"

    # 构建 JSON 数据
    json_data = {
        "food_name": food_name,
        "weight": weight,
        "calories": calories,
    }

    return json_data

@router.post("/recognize-food/")
async def recognize_food(file: UploadFile = File(...)):
    try:
        # 检查文件类型
        if file.content_type not in ALLOWED_FILE_TYPES:
            raise HTTPException(status_code=400, detail="只支持 JPG 或 PNG 格式的图片")

        # 读取上传的图片并转换为 Base64
        image_data = await file.read()
        image_base64 = encode_image_to_base64(image_data)

        # 调用 DashScope API
        response = client.chat.completions.create(
            model="qwen-vl-max-latest",  # 确认模型名称是否正确
            messages=[
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "image_url",
                            "image_url": {"url": f"data:image/jpeg;base64,{image_base64}"},
                        },
                        {
                            "type": "text",
                            "text": (
                                "请识别图片中的食物，并严格按照以下格式返回结果："
                                "食物名称：XXX，重量：XXX，热量：XXX"
                            ),
                        },
                    ],
                }
            ],
        )

        # 解析 DashScope API 的返回结果
        result = response.choices[0].message.content
        print("API 返回结果:", result)  # 打印结果以便调试

        # 将文本数据转换为 JSON 格式
        json_data = text_to_json(result)

        # 返回 JSON 响应
        return JSONResponse(content=json_data)

    except HTTPException as e:
        raise e
    except Exception as e:
        return JSONResponse(content={"error": str(e)}, status_code=500)